<template>
  <div class="chat-input-container">
    <div class="input-toolbar">
      <div class="left-tools">
        <el-tooltip content="上传图片" placement="top">
          <div class="tool-button" @click="triggerImageUpload">
            <i class="fa fa-image"></i>
          </div>
        </el-tooltip>
        
        <el-tooltip content="上传文件" placement="top">
          <div class="tool-button" @click="triggerFileUpload">
            <i class="fa fa-paperclip"></i>
          </div>
        </el-tooltip>
        
        <el-tooltip content="网络搜索" placement="top">
          <div 
            class="tool-button" 
            :class="{'tool-active': webSearchEnabled}"
            @click="webSearchEnabled = !webSearchEnabled"
          >
            <i class="fa fa-globe"></i>
          </div>
        </el-tooltip>
      </div>
      
      <div class="right-tools">
        <el-tooltip :content="clearOnSend ? '清空已发送内容' : '保留已发送内容'" placement="top">
          <div 
            class="tool-button" 
            :class="{'tool-active': clearOnSend}"
            @click="clearOnSend = !clearOnSend"
          >
            <i class="fa fa-eraser"></i>
          </div>
        </el-tooltip>
      </div>
    </div>
    
    <div class="textarea-container">
      <el-input
        v-model="messageText"
        type="textarea"
        :rows="messageRows"
        placeholder="输入消息，按 Shift+Enter 换行，Enter 发送"
        resize="none"
        @keydown.enter.prevent="handleEnterKey"
        ref="messageInput"
      />
      
      <div class="send-button-container">
        <el-button
          type="primary"
          :disabled="!canSendMessage"
          @click="sendMessage"
          class="send-button"
          :loading="sending"
        >
          <i class="fa fa-paper-plane"></i>
        </el-button>
      </div>
    </div>
    
    <div v-if="attachments.length > 0" class="attachments-preview">
      <div 
        v-for="(file, index) in attachments" 
        :key="index"
        class="attachment-item"
      >
        <div class="attachment-preview">
          <template v-if="isImage(file)">
            <img :src="getFilePreview(file)" alt="图片预览" class="image-preview" />
          </template>
          <template v-else>
            <div class="file-icon">
              <i class="fa fa-file-text-o"></i>
            </div>
          </template>
        </div>
        
        <div class="attachment-info">
          <div class="attachment-name" :title="file.name">{{ file.name }}</div>
          <div class="attachment-size">{{ formatFileSize(file.size) }}</div>
        </div>
        
        <div class="attachment-actions">
          <el-button 
            type="danger" 
            size="small" 
            circle 
            @click="removeAttachment(index)"
            class="remove-button"
          >
            <i class="fa fa-times"></i>
          </el-button>
        </div>
      </div>
    </div>
    
    <!-- 隐藏的文件上传输入 -->
    <input 
      type="file" 
      ref="imageInput" 
      accept="image/*" 
      style="display: none" 
      @change="handleImageSelected"
    />
    <input 
      type="file" 
      ref="fileInput" 
      style="display: none" 
      @change="handleFileSelected"
    />
  </div>
</template>

<script setup>
import { ref, computed, nextTick, watch } from 'vue';
import { ElMessage } from 'element-plus';

// 定义属性
const props = defineProps({
  loading: {
    type: Boolean,
    default: false
  },
  modelStatus: {
    type: Object,
    default: () => ({
      connected: false,
      provider: '',
      model: ''
    })
  }
});

// 定义事件
const emit = defineEmits(['send-message', 'upload-attachment']);

// 输入相关变量
const messageText = ref('');
const messageInput = ref(null);
const messageRows = ref(3);
const clearOnSend = ref(true);
const webSearchEnabled = ref(false);
const sending = ref(false);

// 附件相关变量
const attachments = ref([]);
const imageInput = ref(null);
const fileInput = ref(null);
const maxAttachments = 5;
const maxFileSize = 10 * 1024 * 1024; // 10MB

// 计算属性
const canSendMessage = computed(() => {
  return (messageText.value.trim() !== '' || attachments.value.length > 0) && !sending.value;
});

// 监听数据变化
watch(attachments, (newValue) => {
  if (newValue.length > 0) {
    messageRows.value = 2;
  } else {
    messageRows.value = 3;
  }
});

// 聚焦输入框
function focusInput() {
  nextTick(() => {
    messageInput.value?.focus();
  });
}

// 处理Enter键
function handleEnterKey(e) {
  if (e.shiftKey) {
    // Shift+Enter 换行
    return true;
  } else {
    // Enter 发送消息
    sendMessage();
  }
}

// 发送消息
async function sendMessage() {
  if (!canSendMessage.value) {
    return;
  }
  
  // 检查是否有模型连接
  if (!props.modelStatus.connected) {
    ElMessage.warning('当前未连接任何模型，请先在右侧面板配置模型');
    return;
  }
  
  const text = messageText.value.trim();
  if (text === '' && attachments.value.length === 0) {
    return;
  }
  
  sending.value = true;
  
  try {
    // 处理消息的附件
    const messageAttachments = [];
    
    // 上传每个附件
    for (const file of attachments.value) {
      try {
        const attachment = await uploadAttachment(file);
        if (attachment) {
          messageAttachments.push(attachment);
        }
      } catch (error) {
        console.error('上传附件失败:', error);
        ElMessage.error(`上传附件 ${file.name} 失败`);
      }
    }
    
    // 构建消息对象
    const message = {
      content: text,
      web_search: webSearchEnabled.value,
      attachments: messageAttachments
    };
    
    // 触发发送消息事件
    emit('send-message', message);
    
    // 清空消息和附件
    if (clearOnSend.value) {
      messageText.value = '';
      attachments.value = [];
    }
    
    // 聚焦输入框
    focusInput();
  } catch (error) {
    console.error('发送消息失败:', error);
    ElMessage.error('发送消息失败');
  } finally {
    sending.value = false;
  }
}

// 触发图片上传
function triggerImageUpload() {
  if (attachments.value.length >= maxAttachments) {
    ElMessage.warning(`最多只能上传 ${maxAttachments} 个附件`);
    return;
  }
  
  imageInput.value.click();
}

// 处理图片选择
function handleImageSelected(e) {
  const files = e.target.files;
  if (!files || files.length === 0) return;
  
  const file = files[0];
  
  // 检查文件大小
  if (file.size > maxFileSize) {
    ElMessage.error(`文件大小不能超过 ${formatFileSize(maxFileSize)}`);
    e.target.value = null;
    return;
  }
  
  // 检查是否是图片
  if (!file.type.startsWith('image/')) {
    ElMessage.error('请选择图片文件');
    e.target.value = null;
    return;
  }
  
  attachments.value.push(file);
  e.target.value = null;
}

// 触发文件上传
function triggerFileUpload() {
  if (attachments.value.length >= maxAttachments) {
    ElMessage.warning(`最多只能上传 ${maxAttachments} 个附件`);
    return;
  }
  
  fileInput.value.click();
}

// 处理文件选择
function handleFileSelected(e) {
  const files = e.target.files;
  if (!files || files.length === 0) return;
  
  const file = files[0];
  
  // 检查文件大小
  if (file.size > maxFileSize) {
    ElMessage.error(`文件大小不能超过 ${formatFileSize(maxFileSize)}`);
    e.target.value = null;
    return;
  }
  
  attachments.value.push(file);
  e.target.value = null;
}

// 移除附件
function removeAttachment(index) {
  attachments.value.splice(index, 1);
}

// 上传附件到服务器
async function uploadAttachment(file) {
  try {
    // 触发上传附件事件，实际上传操作由父组件处理
    return await emit('upload-attachment', file);
  } catch (error) {
    console.error('上传附件失败:', error);
    throw error;
  }
}

// 获取文件预览
function getFilePreview(file) {
  return URL.createObjectURL(file);
}

// 判断是否为图片
function isImage(file) {
  return file.type.startsWith('image/');
}

// 格式化文件大小
function formatFileSize(bytes) {
  if (bytes < 1024) return bytes + ' B';
  else if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(2) + ' KB';
  else if (bytes < 1024 * 1024 * 1024) return (bytes / (1024 * 1024)).toFixed(2) + ' MB';
  else return (bytes / (1024 * 1024 * 1024)).toFixed(2) + ' GB';
}

// 暴露组件方法
defineExpose({
  focusInput
});
</script>

<style scoped>
.chat-input-container {
  width: 100%;
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  background-color: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.input-toolbar {
  display: flex;
  justify-content: space-between;
  padding: 8px 12px;
  border-bottom: 1px solid #ebeef5;
}

.left-tools, .right-tools {
  display: flex;
  gap: 8px;
}

.tool-button {
  width: 28px;
  height: 28px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  cursor: pointer;
  color: #606266;
  transition: all 0.2s;
}

.tool-button:hover {
  background-color: #f2f6fc;
  color: #409eff;
}

.tool-active {
  background-color: #ecf5ff;
  color: #409eff;
}

.textarea-container {
  position: relative;
  padding: 8px 12px;
}

.textarea-container :deep(.el-textarea__inner) {
  padding-right: 50px;
  font-size: 14px;
  line-height: 1.5;
}

.send-button-container {
  position: absolute;
  right: 16px;
  bottom: 13px;
}

.send-button {
  width: 40px;
  height: 40px;
  padding: 0;
  border-radius: 20px;
}

.attachments-preview {
  max-height: 150px;
  overflow-y: auto;
  padding: 8px 12px;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  border-top: 1px solid #ebeef5;
}

.attachment-item {
  width: calc(25% - 6px);
  min-width: 150px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  position: relative;
}

.attachment-preview {
  height: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
  overflow: hidden;
}

.image-preview {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.file-icon {
  font-size: 32px;
  color: #909399;
}

.attachment-info {
  padding: 6px 8px;
  background-color: #f5f7fa;
}

.attachment-name {
  font-size: 12px;
  color: #303133;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.attachment-size {
  font-size: 11px;
  color: #909399;
  margin-top: 2px;
}

.attachment-actions {
  position: absolute;
  top: 4px;
  right: 4px;
}

.remove-button {
  width: 20px !important;
  height: 20px !important;
  font-size: 10px !important;
  padding: 0 !important;
}
</style> 